package puyu.manage.service.security.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.validation.Assertion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import puyu.manage.service.SysUser.entity.SysUser;
import puyu.manage.service.constant.AjaxResult;
import puyu.manage.service.constant.Constants;
import puyu.manage.service.menu.dao.SysMenuMapper;
import puyu.manage.service.menu.entity.SysMenu;
import puyu.manage.service.menu.service.SysMenuServiceI;
import puyu.manage.service.security.LoginUser;
import puyu.manage.service.security.config.CASAutoConfig;
import puyu.manage.service.security.service.*;
import puyu.manage.service.utils.*;
import puyu.manage.service.utils.tree.Zone;
import puyu.manage.service.utils.tree.ZoneUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 登录验证
 *
 * @author cxnet
 */
@Api(tags = "系统登录")
@RestController
@Slf4j
public class SysLoginController {

    @Autowired(required = false)
    private SysLoginService loginService;

    @Autowired(required = false)
    private SysMenuServiceI menuService;

    @Autowired(required = false)
    private TokenService tokenService;

    @Autowired(required = false)
    private AppLogin appLogin;
    @Autowired(required = false)
    private WebLogin webLogin;


    @Value("${spring.cas.status}")
    private String status;//是否开启单点登录

    @Autowired
    CASAutoConfig casAutoConfig;

    @Autowired(required = false)
    private SysMenuMapper menuMapper;

    /**
     * 登录方法
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public AjaxResult login(@ApiParam(name="params",
            value="datas-数据",required=true) @RequestBody Map<String, Object> params
    ) throws Exception {
        AjaxResult ajax = AjaxResult.success();
        if ("0".equals(status)) {
            return loginService.loginByCas(params);
        }
        Map<String, Object> result = webLogin.login(params);
        String token = (String) result.get("token");
        String type = (String) result.get("type");
        responseValue(token, type, ajax);
        return ajax;
    }

    /**
     * cas sso单点登录
     */
    @GetMapping("/sso")
    public void sso(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        String loginName = (String) session.getAttribute("cas.client.user");
        log.info("ssoLoginName", loginName);
        Assertion assertion = (Assertion) session.getAttribute("_const_cas_assertion");
        String token = "";
        String username = "";

        if (assertion != null) {
            AttributePrincipal principal = assertion.getPrincipal();

            username = principal.getName();
            if (StringUtils.isNull(username)) {
                response.sendRedirect(
                        casAutoConfig.getCasServerLogoutUrl() + "?service=" + URLEncoder.encode(casAutoConfig.getServerName(), Constants.UTF8));
            }
            token = loginService.loginBySso(username);
        } else {
            response.sendRedirect(
                    casAutoConfig.getCasServerLogoutUrl() + "?service=" + URLEncoder.encode(casAutoConfig.getServerName(), Constants.UTF8));
        }
        response.sendRedirect(casAutoConfig.getFrontUrl() + "?s=" + token + "&f=" + status + "&u=" + username);

    }


    /**
     * 响应数据
     *
     * @param token
     * @param type
     * @param ajax
     */
    public void responseValue(String token, String type, AjaxResult ajax) {
        ajax.put(Constants.TOKEN, token);
        if (Constants.SHOW_CHECK.equals(token)) {
            ajax.put(Constants.CODE, 200);
            ajax.put(Constants.MSG, "若密码遗忘，请联系系统管理员，输入错误五次，将锁定当前账号！");
        }
        if (Constants.SUCCESS.equals(token)) {
            ajax.put("data", "1");
            ajax.put(Constants.CODE, 200);
            ajax.put(Constants.MSG, "当前密码强度过低，请修改密码后重新登录！");
        }
        // 密码是否过期
        if (StringUtils.isNotEmpty(type)) {
            ajax.put("data", "1");
            ajax.put(Constants.MSG, "当前密码已过期，请修改密码后重新登录！");
            ajax.put("type", type);
        } else {
            ajax.put("type", "");
        }
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Map<String, Object> user = (Map<String, Object>)loginUser.getUser();
        // 权限集合
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        return ajax;
    }

    /**
     * 移动端登陆
     */
    @PostMapping("/mobileLogin")
    public AjaxResult mobileLogin(@ApiParam(name="params",
            value="datas-数据",required=true) @RequestParam Map<String, Object> params
    ) {
        AjaxResult ajax = AjaxResult.success();
        Map<String, Object> result = appLogin.login(params);
        String token = (String) result.get("token");
        String type = (String) result.get("type");
        responseValue(token, type, ajax);
        return ajax;
    }

    /**
     * 查询当前用户路由信息
     *
     * @return 路由信息
     */
    @ApiOperation("查询当前用户路由信息")
    @GetMapping("/getRouters")
    public AjaxResult getRouters() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        Map<String, Object> user = loginUser.getUser();
        String userId= user.get("userId")+"";
        List<Zone> zones = menuMapper.getRouters(userId);
        return AjaxResult.success(ZoneUtils.buildTree(zones));
    }



}
